﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wabo.Dal.Interface;
using EntityFramework.Extensions;

namespace Wabo.Dal.Repository
{
    public class WaboEFLockRepository : EFBaseRepository, ILocks
    {
        public bool IsLocked(string ipAddress)
        {
            DateTime today = DateTime.Now;
            return Context.IpLocks.FirstOrDefault(r => r.ip_address == ipAddress && r.unlock_date > today) != null;
        }

        public void Lock(string ipAddress, int unlockTime)
        {
            try
            {

                IpLock lockRecord = new IpLock
                {
                    ip_address = ipAddress,
                    lock_date = DateTime.Now,
                    unlock_date = DateTime.Now.AddSeconds(unlockTime)
                };
                Context.IpLocks.Add(lockRecord);
                Context.SaveChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                throw;
            }

        }

        public void Unlock(string ipAddress)
        {
            try
            {
                DateTime today = DateTime.Now;
                Context.IpLocks.Delete(r => r.ip_address == ipAddress && r.unlock_date < today);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                throw;
            }
        }

    }
}
